package biz

import (
	"encoding/json"
	"strconv"
	"time"
	"uwbwebapp/pkg/dao"
	"uwbwebapp/pkg/entities"
	"uwbwebapp/pkg/tools"

	"github.com/google/uuid"
)

func CreateSiteFence(fence *entities.SiteFence) error {
	if fence.Creator == "" {
		fence.Creator = "admin"
	}
	fence.CreateDatetime = time.Now()
	fence.Modifier = fence.Creator
	if fence.Code == "" {
		fence.Code = uuid.NewString()
	}
	fence.ModifyDatetime = fence.CreateDatetime
	err := dao.CreateSiteFence(fence) // 创建第一个围栏，属于泳池围栏。
	if err == nil {
		//创建第二个围栏，属于扩展围栏用于监控告警的，避免出现在第一围栏边缘判断过于精准而造成溺水风险。
		err = CreateBigSiteFence(*fence)

	}
	return err

}
func CreateBigSiteFence(oriFence entities.SiteFence) error {
	//创建第二个围栏，属于扩展围栏用于监控告警的，避免出现在第一围栏边缘判断过于精准而造成溺水风险。
	bigFence := oriFence
	bigFence.Code = "big_" + bigFence.Code

	var polygon []entities.Point
	if bigFence.Coordinate == "" {
		bigFence.Coordinate = `[{"x":0, "y":0}]`
	}
	err := json.Unmarshal([]byte(bigFence.Coordinate), &polygon)
	if err == nil {
		sacleConfig, _ := GetSystemDict("6000")
		floatSc, _ := strconv.ParseFloat(sacleConfig.Value, 64)
		scaledPolygon := tools.ScalePolygon(polygon, (100+floatSc)/100)
		coordiinateTmp, ex := json.Marshal(scaledPolygon)
		if ex == nil {
			bigFence.Coordinate = string(coordiinateTmp)
			ex = dao.CreateSiteFence(&bigFence)
			err = ex
		}

	}
	return err
}

func UpdateSiteFence(fence *entities.SiteFence) error {
	oriFence, err := dao.GetSiteFence(fence.SiteID, fence.Code)
	if err == nil {
		fence.ModifyDatetime = time.Now()
		fence.Creator = oriFence.Creator
		fence.CreateDatetime = oriFence.CreateDatetime
		if fence.Modifier == "" {
			fence.Modifier = "admin"
		}
	}
	err = dao.UpdateSiteFence(fence)
	if err == nil {
		oriFence.Code = "big_" + oriFence.Code

		err = dao.Database.Exec("DELETE FROM site_fence WHERE site_id=? and code=?", oriFence.SiteID, oriFence.Code).Error
		if err == nil {

			err = CreateBigSiteFence(*fence)
		}
	}
	return err
}

func EnumSiteFences(siteId string) ([]entities.SiteFence, error) {
	return dao.EnumSiteFences(siteId)
}

func EnumSiteFenceCodes(siteId string) ([]string, error) {
	return dao.EnumSiteFenceCodes(siteId)
}

func GetSiteFence(siteId string, code string) (entities.SiteFence, error) {
	return dao.GetSiteFence(siteId, code)
}
